package sg.edu.nus.iss.umpire.service.workflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import sg.edu.nus.iss.umpire.dao.UmpireDao;
import sg.edu.nus.iss.umpire.dao.jpa.CompetitionDaoImpl;
import sg.edu.nus.iss.umpire.dao.jpa.UmpireDAOImpl;
import sg.edu.nus.iss.umpire.domain.Competition;
import sg.edu.nus.iss.umpire.domain.CompetitionDay;
import sg.edu.nus.iss.umpire.exception.ServiceException;
import sg.edu.nus.iss.umpire.service.workflow.dto.CompetitionDayDTO;
import sg.edu.nus.iss.umpire.support.HttpMethod;
import sg.edu.nus.iss.umpire.support.Service;
import sg.edu.nus.iss.umpire.support.ServiceConfig;
import sg.edu.nus.iss.umpire.support.ServiceContext;
import sg.edu.nus.iss.umpire.support.StringUtil;

@ServiceConfig(path = "workflow/service", method = HttpMethod.GET)
public class WorkflowGetServiceController implements Service {
	@Override
	public String serve(ServiceContext ctx) throws Exception {

		String page = ctx.getRequest().getParameter("action");

		if (StringUtil.isEmpty(page)) {
			return null;
		} else if ("listSession".equals(page)) {
			return listSession(ctx);
		} else if ("listUmpires".equals(page)){
			return listUmpires(ctx);
		}

		throw new ServiceException("Invalid parameter");
	}
	
	private String listSession(ServiceContext ctx) {
		Long competitionKey = Long.valueOf(ctx.getRequest().getParameter("id"));
		Competition competition = new CompetitionDaoImpl(ctx.getEntityManager()).getByKey(competitionKey);
		List<CompetitionDay> days = competition.getCompetitionDays();

		List<CompetitionDayDTO> result = CompetitionDayDTO.fromEntity(days);
		ctx.getRequest().setAttribute(JSON_DATA, result);
		return JSON_VIEW;
	}
	
	private String listUmpires(ServiceContext ctx) {
		String avails = ctx.getRequest().getParameter("avail"); // ',' seperated ids
		String confirmed = ctx.getRequest().getParameter("confirmed");
		
		UmpireDao dao = new UmpireDAOImpl(ctx.getEntityManager());
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("avail", dao.findUmpireByIds(parseIds(avails)));
		data.put("confirmed", dao.findUmpireByIds(parseIds(confirmed)));
		
		ctx.getRequest().setAttribute(JSON_DATA, data);
		return JSON_VIEW;
	}
	
	private List<Long> parseIds(String ids){
		if (StringUtil.isEmpty(ids)){
			return new ArrayList<Long>();
		}
		
		List<Long> idList = new ArrayList<Long>();
		for (String id : ids.split(",")) {
			idList.add(Long.valueOf(id));
		}
		return idList;
	}

}
